package band.wukong.practice.netty.userguide.objectecho;

import band.wukong.practice.netty.Env;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.ssl.SslContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Desc:
 * author: wukonggg@139.com
 */
public class ObjectEchoClient {

    private static final Logger logger;
    static {
        Env.assemblingLog4j2ConfFile();
        logger  = LogManager.getLogger();
    }

    public static void main(String[] args) throws Exception {
        new ObjectEchoClient().start();
    }

    private void start() throws Exception {
        // Configure SSL.
        final SslContext sslCtx = Env.assemblingSSL(ObjectEchoConst.SSL);

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc(), ObjectEchoConst.HOST, ObjectEchoConst.PORT));
                            }
                            p.addLast(
                                    new ObjectEncoder(),
                                    new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                    new ObjectEchoClientHandler());
                        }
                    });

            // Start the connection attempt.
            b.connect(ObjectEchoConst.HOST, ObjectEchoConst.PORT).sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
